function G=simgame(G)

% SIMGAME: Simulates a 2D/3D MADS game
%
% SYNTAX:
%
%   G = SIMGAME(G)
%   Simulates a 2D/3D MADS game described by an MADS.Game object G.
%
%   The simulation generally may change G and store some simulation data in G.
%   Game object G should be created by function NEWGAME, which specify
%   the players involved and some properties on the game behaviors.
%   A game can involve only one player or many players.
%   All players should be created by function NEWPLAYER, which specify  
%   various properties of each player.
%
% EXAMPLE:
%
%   P1=newplayer('pos',randn(1,2),'motion','random','speed',10,'legend','r')
%   P2=newplayer('pos',randn(1,2),'motion','random','speed',2,'legend','b')
%   G=newgame({P1,P2},'max_step',100,'pause','pause;')
%   G=simgame(G)
%
%  The above example simulates a game with two players with random motion.
%  In this game, players have random initial position, different speeds and colors. 
%  More interesting examples can be seen by running DEMO_MADS.M or EX_*.M.
%   
% See also NEWPLAYER, NEWGAME

%   Author: Hongbin Ma
%   Email:  mathmhb@163.com
%   Last updated: 04/02/09 with MATLAB 6.5
%
%   Problems or suggestions? Email me.


G=draw_game_init(G);
h1=draw_game_board(G);


G.t=G.t0;
G.step=0;
G.TData=[G.t0];

for k=1:G.N,
  G.P{k}.VarsData=[G.P{k}.Vars];
end;

for j=G.plot_components(:),
  if length(G.plot_labels)<j,
    G.plot_labels{j}=['Component [',num2str(j),']'];
  end;
end;
if isempty(G.plot_titles),
  G.plot_titles=G.plot_labels;
end;

while 1;
  if G.draw>0,
    figure(G.figure);
    hold on;
    %~ G=draw_game(G);
    
    if(~isempty(G.before_draw_func)),
      feval(G.before_draw_func,G);
    end;

    G.movie=genmovie(G.movie);
    G.snapshot=gensnapshot(G.snapshot);
    
  end;
  
  q_exit=feval(G.is_gameover_func,G);
  if q_exit, 
    break; 
  end;

  G=step_game(G);
  
  if G.is_gameover>0,
    break;
  end;
  
  if(~isempty(G.after_draw_func)),
    feval(G.after_draw_func,G);
  end;

  eval(G.pause)

  if G.draw>0,
  hh=G.objs_clear;
  for k=1:G.N+1;
      for h=hh{k},
          set(h,'Visible','off');
      end;
  end;
  end;

  hold off;
  
  G.t=G.t+G.h;
  G.step=G.step+1;
  G.TData=[G.TData;G.t];
  for k=1:G.N,
    G.P{k}.VarsData=[G.P{k}.VarsData;G.P{k}.Vars];
  end;
  if G.N==2,
    G.r=norm(G.P{1}.pos-G.P{2}.pos);
  end;
end;

if ~isempty(G.figure_file),
  saveas(G.figure,G.figure_file);
end;
if ~isempty(G.figure2_file),
  saveas(G.figure2,G.figure2_file);
end;


G=draw_game_finish(G);

if ~isempty(G.movie),
  G.movie.aviobj = close(G.movie.aviobj);
end;
